/*
 * Copyright 2010 - Jeremie Brebec
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package org.jb.statemachine.client.impl;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.jb.notification.client.NotificationListener;
import org.jb.statemachine.client.GUIStateHandler;
import org.jb.statemachine.client.State;

import com.google.inject.Inject;
import com.google.inject.Singleton;

@Singleton
public class GUIStateMachine implements NotificationListener<State> {

	/*
	 * 
	 */
	public GUIStateMachine() {
	}
	
	/*
	 * 
	 */
	public <T extends State> void registerStateHandler( GUIStateHandler<T> handler ) {
		mapStateHandler.put( handler.getStateClass(), handler );
	}
	
	/*
	 * 
	 */
	@Inject
	public void setStateHandlers( Set<GUIStateHandler<? extends State>> handlers ) {
		for( GUIStateHandler<? extends State> handler : handlers ) {
			registerStateHandler(handler);
		}
	}
	
	@Override
	public void onNotification(State notification) {
		changeState( notification );
	}
	
	/*
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void changeState( State state ) {
				
		if (state == null)
			return;
		
		GUIStateHandler<State> handler = (GUIStateHandler)mapStateHandler.get( state.getClass() );
		
		if (oldStateHandler != handler) {
			
			if (oldStateHandler != null)
				oldStateHandler.disable();
			
			if (handler != null)
				handler.enable();
		}
		
		if (handler != null)
			handler.update(state);
		
		oldStateHandler = handler;
	}
	
	@Override
	public String getType() {
		return "state";
	}
	
	private Map< Class<?>, GUIStateHandler<? extends State> > mapStateHandler = new HashMap< Class<?>, GUIStateHandler<? extends State> >();
	private GUIStateHandler<? extends State> oldStateHandler = null;
	
	
}
